package org.example.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.example.entity.CasUser;
import org.jasig.cas.client.jaas.AssertionPrincipal;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;


public class CasAuthInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // 从 ActionInvocation 中获取 HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);

        // 获取用户主体
        Object principal = request.getUserPrincipal();
        if (principal instanceof AssertionPrincipal) {
            String username = ((AssertionPrincipal) principal).getName();
            CasUser user = new CasUser();
            user.setName(username);
            // 将用户信息存入 Action 上下文
            invocation.getStack().push(user);
            return invocation.invoke();
        }
        // 未认证重定向到 CAS 登录
        return "casLogin";
    }
}

